
var DIALOG_INFO = 0,
	DIALOG_RESULT_TOUR = 1,
	DIALOG_RESULT_GAME = 2,
	DIALOG_EXIT = 3;

var timer = null;
var blinkTimer = null;
var leftTime = 0;
var timerPause = false;

var medals = [{ru: "medal1.png", en: "en_medal1.png" }, 
		{ru: "medal2.png", en: "en_medal2.png"}, 
		{ru: "medal3.png", en: "en_medal3.png"}];

var tours = [
	{title: "1 тур", titleEn: "1 round", time: 20, titleTotal: "Результаты 1 тура", titleTotalEn: "1st round results",
			text: "Когда начинается ваш ход, у вас есть [time] секунд, чтобы объяснить вашему партнеру слово, написанное на бумажке, не используя однокоренные слова.",
			textEn: "When your turn begins you will have [time] seconds to explain the word in the paper to your partner WITHOUT USING THE WORDS OF THE SAME ROUTE"},
			
	{title: "2 тур", titleEn: "2 round", time: 25, titleTotal: "Результаты 2 тура", titleTotalEn: "2 round results",
			text: "Когда начинается ваш ход, у вас есть [time] секунд, чтобы объяснить вашему партнеру слово, написанное на бумажке, вообще без использования слов.",
			textEn: "In the second round when your turn begins you will have [time] seconds to explain the word in the paper to your partner WITHOUT SAYING ANY SINGLE WORD"},
	
	{title: "3 тур", titleEn: "3 round", time: 15, titleTotal: "Результаты 3 тура", titleTotalEn: "3rd round results",
			text: "Когда начинается ваш ход, у вас есть [time] секунд, чтобы объяснить вашему партнеру слово, написанное на бумажке, произнеся всего одно неоднокоренное слово.",
			textEn: "In the 3rd round when your turn begins you will have [time] seconds to explain the word in the paper to your partner JUST BY SAYING ONE SINGLE WORD NOT OF THE SAME ROUTE."},
];
var curTour = 0;
var tourPlayer = 0;

var results = [];
var isPlayerNotGuess = false;

function openGamePage(isNewGame){
	if(isFirstGame()){
		openGameRule();
		setNotFirstGame();
	}
	if(isNewGame) newGame();
	openPage('game_page');//$.mobile.changePage( $("#game_page") );
}

function newGame(){
	curWord = -1;
	curTour = -1;
	curPlayer = 0;
	curTeam = -1;
	tourPlayer = 0;	
	delete results;
	results = [];
	$("#game_txt_time").text(0);
	
	var step = Math.PI / teams.length;
	var curStep = -Math.PI / 2;
	
	$("#boxCurTeam").empty();
	$("#boxBags").empty();
	$("#circles").empty();
	$("#resultsBody").empty();

	var dir = retina ? 'img2' : 'img';
	
	for (var i = 0; i < teams.length; i++) {
		var team = teams[i];
		team.points = 0;
		team.info = teamsInfo[ team.index ];

		$("#boxCurTeam").append('<div tag="'+i+'" style="background-color: '+team.info.color+'; margin-right: '+10*scale+'px;" class="team_index">'+team.index+'</div>');
		$("#boxBags").append('<div tag="'+i+'" style="background: url('+dir+'/'+team.info.bag+') no-repeat 0 0;" class="bag">0</div>');
	
		$("#resultsBody").append('<tr tag="'+i+'"><td><img class="medal" style="display: none;" /></td>'+
				'<td align="center"><div style="background-color: '+team.info.color+'; opacity: 1; float: none;" class="team_index">'+team.index+'</div></td>'+
				'<td style="padding-left: '+20*scale+'px;"><div class="playersResult">'+
					'<div><div class="name">'+team.players[0]+'</div><div class="total">0</div></div>'+
					'<div><div class="name">'+team.players[1]+'</div><div class="total">0</div></div>'+										
				'</div></td>'+
				'<td align="center"><div class="totalResult">0</div></td></tr>');
	}
	
	var cX = 120*scale, cY = 825*scale, radius = 70*scale; 
	var x, y = 0;	
	
	for (var i = 0; i < teams.length*2; i++) {
		results[i] = {tour: []};
		for(var j = 0; j < tours.length; j++){
			results[i].tour[j] = 0;
		}
		var team = teams[i % teams.length];
		x = cX + radius*Math.cos(curStep);
		y = cY + radius*Math.sin(curStep);
		curStep += step;	

		$("#circles").append('<div class="circle_player" tag="'+i+'" '+
				'style="background-color: '+team.info.color+'; left: '+x+'px; top: '+y+'px;"></div>');
	}	
	
	$("#game_btn_guess").css("display", "none");
	nextTour();
	nextPlayer();
}

function exitGame(){
	pauseSound(clockSound);
	clearInterval(timer);
	$("#game_txt_time").text(0);
	timer = null;
	removeWord();
	$("#game_btn_guess").css("display", "none");
}

function nextPlayer(){
	/*
    if(curTeam >= 0){ 
		if(results[curTeam*2+curPlayer].tour[curTour] == 0){
			playSound(notGuessingSound);
		} else if(!isPlayerNotGuess) {	
			playSound(guessingSound);
		}
	}
	isPlayerNotGuess = false;
    */
	
	if(curTeam >= 0){ 
		if(results[curTeam*2+curPlayer].tour[curTour] == 0){
			playSound(notGuessingSound);
		} else {
			playSound(guessingSound);
		}
	}	
	/*
	tourPlayer++;
	if(tourPlayer >= teams.length*2){
		endTour();
		return;		
	}		
	*/
	curTeam++;
	if(curTeam >= teams.length) {
		curPlayer++;
		curTeam = 0;
		if(curPlayer > 1){
			curPlayer = 0;
			//endTour();
			//return;
		}
	}
	
	var index = curTeam + curPlayer*teams.length;
	
	$(".team_index.active").removeClass("active");
	$(".team_index[tag="+curTeam+"]").addClass("active");	
	
	$(".circle_player.active").removeClass("active");
	$(".circle_player[tag="+index+"]").addClass("active");
	
	$("#boxCurPlayer").css('background-color', teams[curTeam].info.colorA);
	$("#boxCurPlayer span").html(teams[curTeam].players[curPlayer]);
}

function endTour(){
	openDialog(DIALOG_RESULT_TOUR);
}

function nextTour(){
	curTour++;
	tourPlayer = 0;
	if(curTour >= tours.length){
		openDialog(DIALOG_RESULT_GAME);
		return;
	}
	curWord = -1;
	shuffle( words );
	tourWords = words;
	delete passWords;
	passWords = [];
	//curPlayer = 0;
	//curTeam = -1;
	openDialog(DIALOG_INFO);
	//nextPlayer();
}

function guess(){
	teams[curTeam].points++;
	$(".bag[tag = "+curTeam+"]").html(teams[curTeam].points);
	var indexPlayer = curTeam*2 + curPlayer;
	results[indexPlayer].tour[curTour]++;
	newWord();
}

function notGuess(){
	if(timer == null) return;
	passWords.push($(".word span:last").text());
	removeWord();
	newWord();
	isPlayerNotGuess = true;
}

var tourWords = [];
var passWords = [];

function getNewWord(){
	curWord++;
	if(curWord >= tourWords.length) {
		if(passWords.length > 0){
			delete tourWords; 
			tourWords = [];
			tourWords = passWords;
			shuffle( tourWords );
			delete passWords;
			passWords = [];
			curWord = -1;
			return getNewWord();
		} else {
			stopTimer();
			endTour();
			return false;
		}
	}
	return tourWords[curWord];
}

/*
function getNewWord(){
	curWord++;
	if(curWord >= words.length || curWord == 0) {
		curWord = 0;
		shuffle( words );
	}
	return words[curWord];
}
*/
function removeWord(){
	var rword = $(".word");
	if(rword.length){
		rword.css({'-webkit-transform': 'scale(0.4) translate(0px, -1250px)'});
		setTimeout(function(){
			rword.remove();
		}, 400);
	}
}

function newWord(){
	var w = getNewWord();
	if(w != false){
		$("#gameWords").append('<div class="word active" style="-webkit-transform: scale(0.25) translate(0px, '+600*scale+'px);">'+
			'<span class="word-text">'+w+'</span></div>');
		
		setTimeout(function(){
			$(".word.active").css({'-webkit-transform': 'scale(1) translate(0px, 0px)'});
			$(".word.active").removeClass("active");
			playSound(newWordSound);
		}, 1);
	}
}

function tick(){
	if(timerPause) return;
	leftTime--;
	$("#game_txt_time").text(leftTime);
	if(leftTime <= 0){
		stopTimer();
	}
}

function startTimer(){
	stopBlinkPlayer();
	playSound(clockSound);
	timerPause = false;
	leftTime = tours[curTour].time;
	$("#game_txt_time").text(leftTime);
	$("#game_btn_guess").css("display", "block");
	timer = setInterval("tick();", 1000);
	newWord();
}

function stopTimer(){
	if(timer == null) return;
	blinkPlayer();
	pauseSound(clockSound);
	clearInterval(timer);
	$("#game_txt_time").text(0);
	timer = null;
	passWords.push($(".word span").text());
	removeWord();
	nextPlayer();
	$("#game_btn_guess").css("display", "none");
}

function pauseGame(){
	if(timer == null) return;
	timerPause = true;
	pauseSound(clockSound);
}

function resumeGame(){
	if(timer == null) return;
	timerPause = false;
	playSound(clockSound);
}

function getTotalPlayer(index){
	var total = 0;
	for (var i = 0; i < tours.length; i++) {
		total += results[index].tour[i];
	}
	return total;
}
/*
function getChempion(){
	var chempion = 0;
	for (var i = 0; i < teams.length; i++) {
		if(teams[chempion].points <= teams[i].points)
			chempion = i;
	}
	return chempion;
}

function getChempions(){
	var max = 0;
	for (var i = 0; i < teams.length; i++) {
		if(max < teams[i].points)
			max = teams[i].points;
	}
	var chemps = [];
	for (var i = 0; i < teams.length; i++) {
		if(max == teams[i].points)
			chemps.push(i);
	}
	return chemps;
}
*/

function SortByName(a, b){
	return ((a.points < b.points) ? 1 : ((a.points > b.points) ? -1 : 0));
}

function getChempions(){
	var temp = [];
	temp = teams.slice();
	for (var i = 0; i < temp.length; i++) {
		temp[i].i = i;
	}
	temp.sort(SortByName);
	return temp;
}


function openDialog(dialogType){
	$(".dialogBtn").css("display", "none");

	if(dialogType == DIALOG_EXIT){
		$(".gameDialog").removeClass("active");
		$("#exitDialog").addClass("active");
	} else {
		$("#exitDialog").removeClass("active");
		$(".gameDialog").addClass("active");
	}
	
	if(dialogType == DIALOG_RESULT_TOUR || dialogType == DIALOG_RESULT_GAME){
		$("#dialog_text").css("display", "none");
		$("#results").css("display", "block");
		//////////////////////end_tour.currentTime = 0;
		playSound(end_tour);
	}
	
	switch (dialogType) {
	  case DIALOG_INFO:
		var title = isEn() ? tours[curTour].titleEn : tours[curTour].title;
		$("#dialog_title").html(title);
		var text = isEn() ? tours[curTour].textEn : tours[curTour].text;
		$("#dialog_text").html(text.replace(/\[time\]/, tours[curTour].time));	  
		$("#dialog_text").css("display", "block");
		$("#results").css("display", "none");
		$("#dialog_btn_start").css("display", "block");
		break;
	  case DIALOG_RESULT_TOUR:
		$("#dialog_btn_next").css("display", "block");
		var titleTotal = isEn() ? tours[curTour].titleTotalEn : tours[curTour].titleTotal;
		$("#dialog_title").html(titleTotal);
		for (var i = 0; i < teams.length; i++) {
			var total = results[i*2].tour[curTour] + results[i*2+1].tour[curTour];
			var tr = $("tr[tag = "+i+"]");
			tr.find(".totalResult").html(total);
			tr.find(".total:first").html(results[i*2].tour[curTour]);
			tr.find(".total:last").html(results[i*2+1].tour[curTour]);
		}		
		break;
	  case DIALOG_RESULT_GAME:
		$("#dialog_title").html(isEn() ? "Game results" : "Результат игры");
		$("#dialog_btn_ok").css("display", "block");
		$("#dialog_btn_more").css("display", "block");
		for (var i = 0; i < teams.length; i++) {
			var tr = $("tr[tag = "+i+"]");
			tr.find(".totalResult").html(getTotalPlayer(i*2) + getTotalPlayer(i*2+1));
			tr.find(".total:first").html(getTotalPlayer(i*2));
			tr.find(".total:last").html(getTotalPlayer(i*2+1));
		}
		
		var dir = retina ? 'img2' : 'img';
		$(".medal").css("display", "none");
		var chemps = getChempions();
		var i = -1;
		var prevRes = -1;
		for ( index in chemps ) {
			teamIndex = chemps[index].i;
			var m = $("tr[tag = "+teamIndex+"] .medal");
			m.css("display", "block");
			if(prevRes != chemps[index].points){
				prevRes = chemps[index].points;
				i++;
			}
			m.attr("src", dir+'/'+(isEn() ? medals[i].en : medals[i].ru));
			if(i >= medals.length) break;
		}
		
		//$("tr[tag = "+getChempion()+"] .medal").css("display", "block");
		break;
	}
	
	
	$("#gameDialogBlock").css("display", "block");
	//$(".gameDialog").addClass("active");
}

function closeDialog(){
	pauseSound(end_tour);
	$("#gameDialogBlock").css("display", "none");
	$(".gameDialog").removeClass("active");
	$("#exitDialog").removeClass("active");
}

function blinkPlayer(){
	var box = $("#boxCurPlayer");
	blinkTimer = setInterval(function(){
		if(box.hasClass('active')){
			box.removeClass('active');
		} else {
			box.addClass('active');
		}
	}, 1000);
}

function stopBlinkPlayer(){
	if(blinkTimer != null){
		clearInterval(blinkTimer);
		$("#boxCurPlayer").removeClass('active');
	}
}

$(document).ready(function() {
	//newGame();
	$("#game_btn_guess").click(function(){
		removeWord();
		guess();
	});
	
	$("#game_btn_hat").click(function(){
		notGuess();
	});
	
	$("#game_btn_play").click(function(){
		if(timer == null){
			startTimer();
		}
		if(timerPause){
			resumeGame();
		}
	});	
	
	$("#game_btn_pause").click(function(){
		if(timerPause){
			resumeGame();
		} else {
			pauseGame();
		}
	});

	$("#game_btn_stop").click(function(){
		stopTimer();
	});	

	$("#game_btn_menu").click(function(){
		openDialog(DIALOG_EXIT);
		pauseGame();		
	});	

	$("#game_btn_rule").click(function(){
		openRulePage(false);
		//openGameRule();
	});		

	$("#game_btn_help").click(function(){
		openGameRule();
	});		
	
	$("#dialog_btn_start").click(function(){
		closeDialog();
	});		

	$("#dialog_btn_next").click(function(){
		closeDialog();
		nextTour();
	});
	
	$("#dialog_btn_ok").click(function(){
		closeDialog();
		openStarsPage("main_page");
	});
	
	$("#dialog_btn_more").click(function(){
		closeDialog();
		newGame();
	});	
	
	$("#exit_btn_ok").click(function(){
		exitGame();
		closeDialog();
		openStarsPage("main_page");
	});	
	
	$("#exit_btn_cancel").click(function(){
		resumeGame();
		closeDialog();
	});		
});
